import logging
import random

from django import http
# Create your views here.
from django.views import View
from apps.verifications.libs.captcha.captcha import captcha
from django_redis import get_redis_connection
from ronglian_sms_sdk import SmsSDK
from celery_tasks.sms.tasks import send_sms_code

# 2. 创建日志记录器: 导入后创建日志器才能使用
logger = logging.getLogger('django')

class ImageCodeView(View):
    """图形验证码"""

    def get(self, request, uuid):
        # 生成图形验证码
        text, image = captcha.generate_captcha()
        # 保存图形验证码
        redis_conn = get_redis_connection('verify_code')
        redis_conn.setex(f'img_{uuid}', 300, text)

        # 响应返回图形验证码
        return http.HttpResponse(image, content_type='image/jpg')


class SMSCodeView(View):
    """短信验证码"""
    def get(self, request, mobile):
        # 在刚刚的接口的最上方添加如下代码:
        # 链接redis数据库:
        redis_conn = get_redis_connection('verify_code')
        # 从redis数据库中获取存入的数据
        send_flag = redis_conn.get('send_flag_%s' % mobile)
        # 然后判断该数据是否存在, 因为上面的数据只存储60s,
        # 所以如果该数据存在, 则意味着, 不超过60s, 直接返回.
        if send_flag:
            return http.JsonResponse({'code': 400,
                                      'errmsg': '发送短信过于频繁'})


        # 1.接收参数
        image_code_client = request.GET.get("image_code")
        uuid = request.GET.get("image_code_id")
        # 2.校验参数
        if not all([image_code_client, uuid]):
            return http.JsonResponse({
                "cdoe":400,
                "errmsg":"缺少必要的参数"
            })
        # 3.获取redis连接对象
        # 往redis中存入数据, key值和value值随意指定, 但是时间必须为60s
        # 例如这里key:value为:  send_flag_mobile:1  时间为 60

        pl = redis_conn.pipeline()
        pl.setex('send_flag_%s' % mobile, 60, 1)

        # 4.提取图形验证码
        image_code_server = redis_conn.get(f"img_{uuid}")
        if image_code_server is None:
            # 图形验证码已经过期了
            return http.JsonResponse({
                "code":400,
                "errmsg":"验证码已失效"
            })

        # 5.删除图形验证码，避免恶意测试
        try:
            redis_conn.delete(f"img_{uuid}")
        except Exception as e:
            logger.error("删除图形验证码失败,",e)

        # 6.对比图形验证码
        # bytes 转字符串
        image_code_server = image_code_server.decode()
        # 转小写后比较
        if image_code_client.lower() != image_code_server.lower():
            return http.JsonResponse({'code': 400,
                                      'errmsg': '输入图形验证码有误'})

        # 7. 生成短信验证码：生成6位数验证码
        sms_code = '%06d' % random.randint(0, 999999)
        logger.info(sms_code)

        # 8. 保存短信验证码
        # 短信验证码有效期，单位：300秒
        pl.setex('sms_%s' % mobile,
                         300,
                         sms_code)
        pl.execute()

        # 9. 发送短信验证码

        send_sms_code.delay("15626528920",sms_code) #异步发送短信验证码

        # 10. 响应结果
        return http.JsonResponse({'code': 0,
                                  'errmsg': '发送短信成功'})